package com.wzw.springboot.principle.use.security.infrastructure.model;

import org.springframework.security.core.GrantedAuthority;

import java.util.Objects;

/**
 * 自定义认证权限
 *
 * @author Wangzhiwen
 */
public class SecurityAuthority implements GrantedAuthority {

    private String role;

    private String authority;

    public SecurityAuthority() {
    }

    public SecurityAuthority(String role, String authority) {
        this.role = role;
        this.authority = appendPrefix(authority);
    }

    /*
     * @Secured 注解需要拼上ROLE_前缀
     * @PreAuthorize 注解使用SPEL表达式时，hasAnyRole会判断传入的值有没有ROLE_前缀，没有时会自动拼上。hasAuthority则不会自动拼上ROLE_前缀
     *               hasPermission 默认的实现会直接返回false，需要自己定义实现逻辑
     */
    private String appendPrefix(String code) {
        if (code.contains("ROLE_")) {
            return code;
        }
        return "ROLE_" + code;
    }

    @Override
    public String getAuthority() {
        return authority;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public void setAuthority(String authority) {
        this.authority = authority;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof SecurityAuthority)) return false;
        SecurityAuthority that = (SecurityAuthority) o;
        return Objects.equals(role, that.role) && Objects.equals(authority, that.authority);
    }

    @Override
    public int hashCode() {
        return Objects.hash(role, authority);
    }
}
